//
//  UIImageView+Gestures.m
//  JewelryStore
//
//  Created by lcs on 16/10/11.
//  Copyright © 2016年 com. All rights reserved.
//

#import "UIImageView+Gestures.h"

@implementation UIImageView (Gestures)

- (instancetype)initWithImage:(UIImage *)image andFrame:(CGRect)frame addSuperView:(UIView *)superView
{
    self = [super init];
    if (self) {
        
        self.image = image;
        self.frame = frame;
        self.userInteractionEnabled = YES;
        [self addGestures];
        [superView addSubview:self];

    }

    return self;
}

- (void)addGestures
{
    //添加手势
    UIPanGestureRecognizer *regcognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [self addGestureRecognizer:regcognizer];
    
    UIPinchGestureRecognizer *pin = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
    pin.delegate = self;
    [self addGestureRecognizer:pin];
    
    UIRotationGestureRecognizer *rotate = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotation:)];
    rotate.delegate = self;
    [self addGestureRecognizer:rotate];

}
//拖动手势
- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    
    //执行多次的translation增量
    if (recognizer.state < UIGestureRecognizerStateEnded)
    {
        //跟随手指移动
        CGPoint offset = [recognizer translationInView:self.superview];
        self.transform = CGAffineTransformTranslate(self.transform, offset.x, offset.y);
        //清零translation
        [recognizer setTranslation:CGPointZero inView:self];
        
    }
}

//处理捏合手势
- (void)handlePinch:(UIPinchGestureRecognizer *)recognizer
{
//    [self.superview bringSubviewToFront:self];
    CGFloat scale = recognizer.scale;
    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, scale, scale);
    recognizer.scale = 1.0;
}

//处理旋转手势
- (void)handleRotation:(UIRotationGestureRecognizer *)recognizer
{
//    [self.superview bringSubviewToFront:self];
    recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation);
    recognizer.rotation = 0.0;
}

//判断两个手势能不能同时进行
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    //1.如果当前已经识别的手势是捏合的，另外一个想要被识别的是旋转的
    //2.或者当前的是旋转、另外一个是捏合，
    //以上两种条件满足一个，就可以让两个手势的事件都执行
    if (([gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]] && [otherGestureRecognizer isKindOfClass:[UIRotationGestureRecognizer class]])
        ||
        ([otherGestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]] && [gestureRecognizer isKindOfClass:[UIRotationGestureRecognizer class]])) {
        return YES;
    }
    return NO;
}


@end
